<template>
  <Layout>
    <div class="customer-list-container">
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>客户列表</span>
            <div class="header-actions">
              <el-button type="primary" @click="handleAddCustomer"
                >新增客户</el-button
              >
              <el-button>批量导入</el-button>
              <el-button>导出数据</el-button>
            </div>
          </div>
        </template>

        <div class="search-bar">
          <el-form :inline="true" :model="searchForm" class="demo-form-inline">
            <el-form-item label="客户名称">
              <el-input
                v-model="searchForm.name"
                placeholder="请输入客户名称"
                clearable
              />
            </el-form-item>
            <el-form-item label="手机号码">
              <el-input
                v-model="searchForm.phone"
                placeholder="请输入手机号码"
                clearable
              />
            </el-form-item>
            <el-form-item label="会员等级">
              <el-select
                v-model="searchForm.memberLevel"
                placeholder="请选择会员等级"
                clearable
              >
                <el-option label="全部等级" value="" />
                <el-option
                  v-for="level in memberLevels"
                  :key="level.level"
                  :label="level.name"
                  :value="level.level"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="注册时间">
              <el-date-picker
                v-model="searchForm.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-table
          v-loading="loading"
          :data="customerList"
          style="width: 100%"
          border
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="name" label="客户名称" />
          <el-table-column prop="phone" label="手机号码" />
          <el-table-column prop="memberLevel" label="会员等级">
            <template #default="scope">
              <el-tag :type="getMemberLevelType(scope.row.memberLevel)">
                {{ getMemberLevelName(scope.row.memberLevel) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="totalAmount" label="累计消费" sortable>
            <template #default="scope">
              <span>¥{{ scope.row.totalAmount.toFixed(2) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="orderCount" label="订单数" sortable />
          <el-table-column prop="lastOrderTime" label="最近下单" sortable />
          <el-table-column prop="registerTime" label="注册时间" sortable />
          <el-table-column label="操作" width="180">
            <template #default="scope">
              <el-button type="primary" link @click="handleEdit(scope.row)"
                >编辑</el-button
              >
              <el-button
                type="success"
                link
                @click="handleViewDetail(scope.row)"
                >查看</el-button
              >
              <el-button type="danger" link @click="handleDelete(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
  </Layout>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import Layout from "@/components/Layout.vue";
import MemberService from "@/services/MemberService";
import type { MemberLevel } from "@/services/MemberService";

// 搜索表单
const searchForm = reactive({
  name: "",
  phone: "",
  memberLevel: "",
  dateRange: [] as string[],
});

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 数据加载状态
const loading = ref(false);

// 会员等级数据
const memberLevels = ref<MemberLevel[]>([]);

// 客户列表数据（模拟数据）
const customerList = ref([
  {
    id: 1,
    name: "张三",
    phone: "13812345678",
    memberLevel: "VIP1",
    totalAmount: 1234.56,
    orderCount: 5,
    lastOrderTime: "2023-06-15",
    registerTime: "2023-01-10",
  },
  {
    id: 2,
    name: "李四",
    phone: "13987654321",
    memberLevel: "VIP2",
    totalAmount: 3456.78,
    orderCount: 8,
    lastOrderTime: "2023-06-18",
    registerTime: "2023-02-15",
  },
  {
    id: 3,
    name: "王五",
    phone: "13566778899",
    memberLevel: "VIP3",
    totalAmount: 6789.12,
    orderCount: 12,
    lastOrderTime: "2023-06-19",
    registerTime: "2023-03-20",
  },
]);

// 初始化数据
onMounted(async () => {
  await fetchMemberLevels();
  await fetchCustomerList();
});

// 获取会员等级列表
const fetchMemberLevels = async () => {
  try {
    memberLevels.value = await MemberService.getMemberLevels();
  } catch (error) {
    console.error("获取会员等级列表失败:", error);
  }
};

// 获取客户列表（模拟数据）
const fetchCustomerList = async () => {
  loading.value = true;
  try {
    // 模拟API请求延迟
    await new Promise((resolve) => setTimeout(resolve, 500));

    // 这里应该是实际的API调用
    // const response = await CustomerService.getCustomerList({
    //   page: currentPage.value,
    //   pageSize: pageSize.value,
    //   ...searchForm
    // });

    // customerList.value = response.data;
    // total.value = response.total;

    // 模拟总数据量
    total.value = 58;
  } catch (error) {
    console.error("获取客户列表失败:", error);
    ElMessage.error("获取客户列表失败，请稍后重试");
  } finally {
    loading.value = false;
  }
};

// 根据会员等级获取显示名称
const getMemberLevelName = (level: string) => {
  const memberLevel = memberLevels.value.find((item) => item.level === level);
  return memberLevel ? memberLevel.name : level;
};

// 根据会员等级获取标签类型
const getMemberLevelType = (level: string) => {
  const types = {
    VIP1: "",
    VIP2: "success",
    VIP3: "warning",
    VIP4: "danger",
    VIP5: "danger",
    VIP6: "danger",
  };
  return types[level as keyof typeof types] || "";
};

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchCustomerList();
};

// 重置搜索条件
const resetSearch = () => {
  Object.keys(searchForm).forEach((key) => {
    if (key === "dateRange") {
      searchForm[key] = [];
    } else {
      searchForm[key] = "";
    }
  });
  handleSearch();
};

// 处理分页大小变化
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  fetchCustomerList();
};

// 处理页码变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  fetchCustomerList();
};

// 新增客户
const handleAddCustomer = () => {
  ElMessage.info("新增客户功能开发中...");
};

// 编辑客户
const handleEdit = (row: any) => {
  ElMessage.info(`编辑客户：${row.name}`);
};

// 查看客户详情
const handleViewDetail = (row: any) => {
  ElMessage.info(`查看客户详情：${row.name}`);
};

// 删除客户
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`确定要删除客户"${row.name}"吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      // 这里应该调用删除API
      // await CustomerService.deleteCustomer(row.id);

      ElMessage.success("删除成功");
      fetchCustomerList();
    })
    .catch(() => {
      // 取消删除
    });
};
</script>

<style scoped>
.customer-list-container {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-bar {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
